from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import FileResponse
from services import comic_downloader
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

def download_tool(id: str):
    comic_downloader.add_comic_lst(id)
    if comic_downloader.bp==False:
        comic_downloader.download_albums()

@app.get("/download/{id}")
async def download(id: str,background_tasks: BackgroundTasks):
    name=comic_downloader.searchName(id)
    # 定义PDF文件的最终路径
    pdf_file_path = comic_downloader.pdf_abs_path / f"{name}.pdf"
    if pdf_file_path.exists():
        return FileResponse(str(pdf_file_path), media_type='application/pdf', filename=f"{name}.pdf")
    background_tasks.add_task(download_tool, id)
    return {"message": "任务已开始\n"+str(comic_downloader.comic_list)}